import serial
import time
import json
from datetime import datetime, timezone, timedelta
import random

# 配置虚拟串口号和波特率
SERIAL_PORT = 'COM4'  
BAUD_RATE = 9600

# 时间配置（北京时间 UTC+8）
DAY_START_HOUR = 5   # 白天开始时间（早上5点）
NIGHT_START_HOUR = 19  # 黑夜开始时间（晚上7点）

# 白天参数范围
TEMP_DAY_MIN, TEMP_DAY_MAX = 25.0, 30.0
HUMI_DAY_MIN, HUMI_DAY_MAX = 40.0, 60.0
LIGHT_DAY_MIN, LIGHT_DAY_MAX = 50.0, 100.0

# 夜间参数范围
TEMP_NIGHT_MIN, TEMP_NIGHT_MAX = 18.0, 22.0
HUMI_NIGHT_MIN, HUMI_NIGHT_MAX = 60.0, 80.0
LIGHT_NIGHT = 0.0


# 判断当前是否是白天
def is_daytime(now: datetime) -> bool:
    hour = now.hour
    return DAY_START_HOUR <= hour < NIGHT_START_HOUR

# 生成模拟数据
def generate_sensor_data():
   
    now_utc = datetime.now(timezone.utc)
    now_beijing = now_utc + timedelta(hours=8)

    is_day = is_daytime(now_beijing)

    if is_day:
        temperature = round(random.uniform(TEMP_DAY_MIN, TEMP_DAY_MAX), 1)
        humidity = round(random.uniform(HUMI_DAY_MIN, HUMI_DAY_MAX), 1)
        light = round(random.uniform(LIGHT_DAY_MIN, LIGHT_DAY_MAX), 1)
    else:
        temperature = round(random.uniform(TEMP_NIGHT_MIN, TEMP_NIGHT_MAX), 1)
        humidity = round(random.uniform(HUMI_NIGHT_MIN, HUMI_NIGHT_MAX), 1)
        light = LIGHT_NIGHT

    return {
        "timestamp": now_beijing.isoformat(),
        "data": [temperature, humidity, light]
    }


# 每1分钟发送模拟数据到串口
def run_serial_sender():
    try:
        with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
            print(f"[串口] 正在通过 {SERIAL_PORT} 发送数据...")
            while True:
                data = generate_sensor_data()
                payload = json.dumps(data) + "\n"  # 添加换行符分隔
                ser.write(payload.encode())
                print(f"[串口] 发送数据: {payload.strip()}")
                time.sleep(60)
    except serial.SerialException as e:
        print(f"[错误] 串口发送失败: {e}")


if __name__ == '__main__':
    run_serial_sender()